package com.weavernorth.humanresource;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.util.Iterator;

/**
 * @program: ecology_erdos
 * @description: 工资核算范围推送SAP判断是否锁定
 * @author: zm
 * @create: 2020-02-27 14:10
 **/


public class SalarRangeUtil {
    private static Log log = LogFactory.getLog(SalarRangeUtil.class);

    /**
     * 推送SAP,判断是否锁定
     *
     * @param strGzfw SAP工资范围
     * @param strSxrq 生效日期
     * @return
     */
    public String judgeLock(String strGzfw, String strSxrq) {
        //返回值
        String strMessage = "";
        //基础类
        BaseBean bb = new BaseBean();
        //返回标识
        String testType = "";
        //拼接xml
        StringBuffer requestXml = new StringBuffer();
        requestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>");
        requestXml.append("<soapenv:Header/>");
        requestXml.append("<soapenv:Body>");
        requestXml.append("<urn:ZHRI_080>");
        requestXml.append("<IV_ABKRS>" + strGzfw + "</IV_ABKRS>");
        requestXml.append("<IV_BEGDA>" + strSxrq + "</IV_BEGDA>");
        requestXml.append("<RETURN>");
        requestXml.append("<item>");
        requestXml.append("<TYPE></TYPE>");
        requestXml.append("<ID></ID>");
        requestXml.append("<NUMBER></NUMBER>");
        requestXml.append("<MESSAGE></MESSAGE>");
        requestXml.append("<LOG_NO></LOG_NO>");
        requestXml.append("<LOG_MSG_NO></LOG_MSG_NO>");
        requestXml.append("<MESSAGE_V1></MESSAGE_V1>");
        requestXml.append("<MESSAGE_V2></MESSAGE_V2>");
        requestXml.append("<MESSAGE_V3></MESSAGE_V3>");
        requestXml.append("<MESSAGE_V4></MESSAGE_V4>");
        requestXml.append("<PARAMETER></PARAMETER>");
        requestXml.append("<ROW></ROW>");
        requestXml.append("<FIELD></FIELD>");
        requestXml.append("<SYSTEM></SYSTEM>");
        requestXml.append("</item>");
        requestXml.append("</RETURN>");
        requestXml.append("</urn:ZHRI_080>");
        requestXml.append("</soapenv:Body>");
        requestXml.append("</soapenv:Envelope>");
        log.info("判断工资范围是否锁定,推送xml:" + requestXml);
        String strGzfwUrl = Util.null2String(bb.getPropValue("personnel-erdos", "gzfwurl"));
        log.info("工资范围推送路径:" + strGzfwUrl);
        try {
            String strReturnMessage = sendPost(strGzfwUrl, requestXml.toString(), "utf-8");
            //解析返回值:
            Document doc = null;

            doc = DocumentHelper.parseText(strReturnMessage.toString());
            Iterator<Element> its2 = doc.selectNodes("//TYPE").iterator();
            while (its2.hasNext()) {
                Element element = its2.next();
                testType = element.getText();
                if (!"".equals(testType)) {
                    bb.writeLog("testType值为:" + testType + "\n");
                    break;
                }

            }
            //返回值失败时,则提示失败
            if ("E".equals(testType)) {
                Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                while (its3.hasNext()) {
                    Element element2 = its3.next();
                    strMessage = element2.getText();
                    if (!"".equals(strMessage)) {
                        break;
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMessage;
    }


    /**
     * 推送方法
     *
     * @param strUrl
     * @param strRequestXml
     * @param strEncoding
     * @return
     * @throws IOException
     */
    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);

            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);
            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("personnel-erdos", "username"));
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("personnel-erdos", "password"));
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                // log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /**
     * 根据工资范围id得到工资范围bpm值
     *
     * @param strGzfwId
     * @return
     */
    public String getGzfw(String strGzfwId) {
        RecordSet rs = new RecordSet();
        //返回值
        String strGzhsfw = "";
        String sql = "select gzhsfw from uf_gzfw where id = ?";
        rs.executeQuery(sql, strGzfwId);
        if (rs.next()) {
            strGzhsfw = Util.null2String(rs.getString("gzhsfw"));
        }
        return strGzhsfw;

    }


    /**
     * 根据人员id得到工资范围bpm值
     *
     * @param strUserid
     * @return
     */
    public String getGzfwFromUser(String strUserid) {
        RecordSet rs = new RecordSet();
        //返回值
        String strGzhsfw = "";
        String sql = "select gzhsfw from uf_gzfw ug,cus_fielddata cf  where ug.id=cf.field23  and cf.id=? and cf.scopeid='1'";
        rs.executeQuery(sql, strUserid);
        if (rs.next()) {
            strGzhsfw = Util.null2String(rs.getString("gzhsfw"));
        }
        return strGzhsfw;

    }


    /**
     * 根据表名和字段名得到fieldid
     *
     * @param strMainTable   主表名称
     * @param strDetailTable 明细表名称
     * @param strFieldName   字段名称
     * @return fieldid
     */

    public String getFieldid(String strMainTable, String strDetailTable, String strFieldName) {
        //返回id
        String strReturn = "";
        //数据库操作
        RecordSet rs = new RecordSet();
        //查询sql
        String strSql = "select id from workflow_billfield  where billid=(select id from workflow_bill where tablename=?) and fieldname=?";
        if (!"".equals(strDetailTable)) {
            strSql = strSql + " and detailtable='" + strDetailTable + "'";
        }
        rs.executeQuery(strSql, strMainTable, strFieldName);
        log.info("查询字段id的sql:" + strSql + ",strMainTable:" + strMainTable + ",strFieldName:" + strFieldName);
        if (rs.next()) {
            strReturn = Util.null2String(rs.getString("id"));
        }
        return strReturn;

    }

    /**
     * 得到下拉框选中对应的值
     *
     * @param strFieldid
     * @param strSelectValue
     * @return
     */
    public String getFieldValue(String strFieldid, String strSelectValue) {
        //返回值
        String strSelectName = "";
        //数据库操作
        RecordSet rs = new RecordSet();
        String sql = "select selectname from workflow_selectitem where fieldid=? and selectvalue=?";
        rs.executeQuery(sql, strFieldid, strSelectValue);
        log.info("得到下拉框选中的值的sql:" + sql + ",strField:" + strFieldid + ",strSelectValue:" + strSelectValue);
        if (rs.next()) {
            strSelectName = Util.null2String(rs.getString("selectname"));
        }
        return strSelectName;

    }

    /**
     * 根据员工id得到员工编码
     *
     * @param strUserid 员工id
     * @return 员工编码
     */
    public String getWorkcode(String strUserid) {
        String strWorkcode = "";
        RecordSet rs = new RecordSet();
        String strSql = "select workcode from hrmresource where id=?";
        rs.executeQuery(strSql, strUserid);
        if (rs.next()) {
            strWorkcode = Util.null2String(rs.getString("workcode"));
        }

        return strWorkcode;

    }

    /**
     * 根据员工员工编码得到员工id
     *
     * @param strWorkcode 员工编码
     * @return 员工编码
     */
    public String getUserid(String strWorkcode) {
        String strUserid = "";
        RecordSet rs = new RecordSet();
        String strSql = "select id from hrmresource where workcode=?";
        rs.executeQuery(strSql, strWorkcode);
        if (rs.next()) {
            strUserid = Util.null2String(rs.getString("id"));
        }

        return strUserid;

    }
}
